<template>
    <div class="UserControl">
        <!-- 主要内容（form表单） -->

        <el-row>
            <el-col :span="24">
                <el-card>

                    <div slot="header" class="clearfix">
                        <el-button type="primary" size="default" icon="el-icon-plus" @click="adduser(0)">新建</el-button>
                    </div>

                    <el-col :span="4" style="padding-bottom: 15px">
                        <el-card>
                            <div slot="header" class="clearfix">
                                <span>组织机构</span>
                            </div>

                            <el-input placeholder="输入关键字进行过滤"  maxlength="20"
  show-word-limit v-model="filterText">
                            </el-input>

                            <el-tree @node-click="selectUsers" class="filter-tree" :data="OrganizationTree"
                                     :props="defaultProps" default-expand-all :filter-node-method="filterNode"
                                     ref="tree">
                            </el-tree>
                        </el-card>
                    </el-col>


                    <!-- 右边 点击 组织机构 显示 详情 ，并且能够修改 -->
                    <el-col :span="20" style="padding-bottom: 15px">
                        <el-card>
                            <el-form ref="form" label-width="80px" :inline="true" :model="selectOrganizationForm"
                                     :rules="rules" @keyup.enter.native="onSubmit()">
                                <el-form-item label="机构名称" prop="name">
                                    <el-input v-model="selectOrganizationForm.name"  maxlength="10"
  show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="机构简称" prop="abbreviation">
                                    <el-input v-model="selectOrganizationForm.abbreviation"  maxlength="10"
  show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="上级机构" prop="superior">
                                    <el-cascader v-model="selectOrganizationForm.superior" :options="OrganizationTree"
                                                 :props="optionProps" @change="handleChange"></el-cascader>
                                </el-form-item>
                                <el-form-item label="机构编号" prop="number">
                                    <el-input v-model="selectOrganizationForm.number"  maxlength="20"
  show-word-limit placeholder="请输入机构编码"></el-input>
                                </el-form-item>
                                <el-form-item label="联系人" prop="linkman">
                                    <el-input v-model="selectOrganizationForm.linkman"  maxlength="15"
  show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="联系电话" prop="phone">
                                    <el-input v-model="selectOrganizationForm.phone"  maxlength="11"
  show-word-limit></el-input>
                                </el-form-item>
                                <el-form-item label="所在地点" class="morewidth" >
<!--                                    <div class="linkage">-->
<!--                                        <div>-->
<!--                                            <el-select v-model="selectProvince" filterable size="medium"-->
<!--                                                       @change="selectProvinceFun(selectProvince)" placeholder="请选择省份">-->
<!--                                                <el-option :value="index" :label="item.name"-->
<!--                                                           v-for="(item, index) in city" :key="index"></el-option>-->
<!--                                            </el-select>-->
<!--                                        </div>-->
<!--                                        <div>-->
<!--                                            <el-select v-model="selectCity" filterable size="medium"-->
<!--                                                       @change="selectCityFun(selectCity)" placeholder="请选择城市">-->
<!--                                                <el-option :value="index" :label="item.name"-->
<!--                                                           v-for="(item, index) in cityList" :key="index"></el-option>-->
<!--                                            </el-select>-->
<!--                                        </div>-->
<!--                                        <div>-->
<!--                                            <el-select v-model="selectArea" filterable size="medium"-->
<!--                                                       @change="selectAreaFun(selectArea)" placeholder="请选择区县">-->
<!--                                                <el-option :value="index" :label="item.name"-->
<!--                                                           v-for="(item, index) in areaList" :key="index"></el-option>-->
<!--                                            </el-select>-->
<!--                                        </div>-->
                                    <el-cascader
                                        v-model="selectOrganizationForm.selectArea"
                                        :options="city"
                                        @change="handleChange"></el-cascader>
                                        <el-input v-model="selectOrganizationForm.selectDetails"
                                                  placeholder="详细地址" style="width: 100%"  maxlength="50"
  show-word-limit></el-input>
<!--                                    </div>-->
                                </el-form-item>
                                <el-form-item label="备注" class="desc">
                                    <el-input type="textarea"   maxlength="255"
  show-word-limit v-model="selectOrganizationForm.remark"></el-input>
                                </el-form-item>
                            </el-form>
                            <el-row :gutter="20">
                                <el-col :span="2" :offset="21">
                                    <el-button type="primary" @click="onSubmit('selectOrganizationForm')"
                                               style="margin-right: 30px">保存
                                    </el-button>
                                </el-col>
                            </el-row>
                        </el-card>
                    </el-col>

                    <!-- 新建组织机构弹窗 -->
                    <el-dialog :title="isAddOrEdit ? '新建组织机构' : '修改组织机构'" :visible.sync="dialogFormVisible" width="40%"
                               :destroy-on-close="true">
                        <el-form ref="form" label-width="80px" :inline="true" :model="addOrganizationForm"
                                 :rules="rulesAddOrganizationForm" @keyup.enter.native="onSubmit()">
                            <el-form-item label="机构名称" prop="name">
                                <el-input v-model="addOrganizationForm.name"  maxlength="10"
  show-word-limit></el-input>
                            </el-form-item>
                            <el-form-item label="机构简称" prop="abbreviation">
                                <el-input v-model="addOrganizationForm.abbreviation"  maxlength="10"
  show-word-limit></el-input>
                            </el-form-item>

                            <el-form-item label="上级机构" prop="superior">
                                <el-cascader v-model="addOrganizationForm.superior" :options="OrganizationTree"
                                             :props="optionProps" @change="handleChange"></el-cascader>
                            </el-form-item>

                            <el-form-item label="机构编号" prop="number">
                                <el-input v-model="addOrganizationForm.number"  maxlength="20"
  show-word-limit placeholder="请输入机构编码"></el-input>
                            </el-form-item>

                            <el-form-item label="联系人"  prop="linkman">
                                <el-input  maxlength="15"
  show-word-limit v-model="addOrganizationForm.linkman"></el-input>
                            </el-form-item>

                            <el-form-item label="联系电话" prop="phone">
                                <el-input v-model="addOrganizationForm.phone"  maxlength="11"
  show-word-limit></el-input>
                            </el-form-item>

                            <el-form-item label="所在地点" class="morewidth">
<!--                                <div class="linkage">-->
<!--                                    <div>-->
<!--                                        <el-select v-model="selectProvince" filterable size="medium"-->
<!--                                                   @change="selectProvinceFun(selectProvince)" placeholder="请选择省份">-->
<!--                                            <el-option :value="index" :label="item.name" v-for="(item, index) in city"-->
<!--                                                       :key="index"></el-option>-->
<!--                                        </el-select>-->
<!--                                    </div>-->
<!--                                    <div>-->
<!--                                        <el-select v-model="selectCity" filterable size="medium"-->
<!--                                                   @change="selectCityFun(selectCity)" placeholder="请选择城市">-->
<!--                                            <el-option :value="index" :label="item.name"-->
<!--                                                       v-for="(item, index) in cityList" :key="index"></el-option>-->
<!--                                        </el-select>-->
<!--                                    </div>-->
<!--                                    <div>-->
<!--                                        <el-select v-model="selectArea" filterable size="medium"-->
<!--                                                   @change="selectAreaFun(selectArea)" placeholder="请选择区县">-->
<!--                                            <el-option :value="index" :label="item.name"-->
<!--                                                       v-for="(item, index) in areaList" :key="index"></el-option>-->
<!--                                        </el-select>-->
<!--                                    </div>-->
                                <el-cascader
                                    v-model="addOrganizationForm.addArea"
                                    :options="city"
                                    @change="handleChange"></el-cascader>
                                <el-input v-model="addOrganizationForm.addDetails"
                                          placeholder="详细地址"  maxlength="50"
  show-word-limit></el-input>
<!--                                </div>-->
                            </el-form-item>
                            <el-form-item label="备注" >
                                <el-input type="textarea" style="width:100%"  maxlength="255"
  show-word-limit v-model="addOrganizationForm.remark"></el-input>
                            </el-form-item>
                        </el-form>

                        <el-row>
                            <el-col :span="24" class="text-center">
                                <el-button @click="dialogFormVisible = false">取消</el-button>
                                <el-button type="primary" @click="onSubmit('addOrganizationForm')">保存</el-button>
                            </el-col>
                        </el-row>
                    </el-dialog>
                </el-card>
            </el-col>
        </el-row>
    </div>
</template>

<script>
import {
    convertKey
} from "@/library";
import {
    mapGetters
} from "vuex";
import axios from "@/api/request.js";
import city from "/public/area";

export default {
    name: "UserControl",
    data() {
        return {
            addOrganizationForm: {
                name: "", //名称
                abbreviation: "", //简称
                superior: [], //上级
                number: "", //编号
                linkman: "", //联系人
                phone: "", //电话
                remark: "", //备注
                addArea: [], // 省市区三级联动
                addDetails: '', // 详细地址
                detailedAddress: "", //详细地址汇总
            },

            selectOrganizationForm: {
                name: "", //名称
                abbreviation: "", //简称
                superior: [], //上级
                number: "", //编号
                linkman: "", //联系人
                phone: "", //电话
                remark: "", //备注
                selectArea: [], // 省市区三级联动
                selectDetails: '', // 详细地址
                detailedAddress: "", //详细地址汇总
            },
            tableData: [],
            // 总数据
            city: city,
            optionsLevel: [{
                value: 3,
                label: '区级管理员'
            }, {
                value: 4,
                label: '镇街管理员'
            }, {
                value: 5,
                label: '村居信息员'
            }],

            townIndex: 0,
            isAddOrigan: false,
            defaultProps: {
                children: "children",
                label: "label",
            },
            roleList: [],
            optionProps: {
                value: 'value',
                label: 'label'
            },
            filterText: "",
            dialogFormVisible: false,
            form: {
                account: "",
                userName: "",
                password: "",
                password2: "",
                organization: [],
                phone: "",
                userId: "",
                level: "",
                roleId: "",
                roleIds: [],
                idCard: "",
                subjectTownId: "", //所属镇 (区域编码) 必填
                subjectVillageId: "", //所属村 (区域编码)
                administrativeCode: "", //行政编码
            },
            search: "",
            checked: false,
            rulesAddOrganizationForm:{
                name: [{
                required: true,
                message: "名称不能为空",
                trigger: ["change","blur"],
            }], //名称
                abbreviation: [{
                required: true,
                message: "简称不能为空",
                trigger: ["change","blur"],
            }], //简称
                superior: [{
                required: true,
                message: "上级不能为空",
                trigger: ["change","blur"],
            }], //上级
                number: [{
                required: true,
                message: "编号不能为空",
                trigger: ["change","blur"],
            }], //编号
                linkman: [{
                required: true,
                message: "联系人不能为空",
                trigger: ["change","blur"],
            }], //联系人
                phone: [{
                required: true,
                message: "联系电话不能为空",
                trigger: ["change","blur"],
            }], //电话
                remark:[{
                required: true,
                message: "备注不能为空",
                trigger: ["change","blur"],
            }], //备注
                addArea: [], // 省市区三级联动
                addDetails: [{
                required: true,
                message: "详细地址不能为空",
                trigger: ["change","blur"],
            }], // 详细地址
                detailedAddress:[{
                required: true,
                message: "详细地址汇总不能为空",
                trigger: ["change","blur"],
            }], //详细地址汇总
            },

            subjectTownId: [{
                required: true,
                message: "请至少选择一项",
                trigger: "change",
            },],

            props: {
                children: "children",
                label: "label",
            },
            params: {
                pageNumber: 1,
                pageSize: 10,
            },
            OrganizationTree: [],
            paging: {},
            List: [],
            OrganizationList: [],
            row: {},
            disabled: false,
            lookdialogFormVisible: false,
            detail: {},
            documentClick: false,
            filterList: [],
            isAddOrEdit: true,
            //正则验证
            rules: {
                name: [{
                    required: true,
                    message: "请输入部门名称",
                    trigger: "blur",
                },],
                abbreviation: [{
                    required: true,
                    message: "请输入部门简称",
                    trigger: "blur",
                },],
                // superior: [{
                //     required: true,
                //     message: "请选择上级机构",
                //     trigger: "blur",
                // }],
                number: [{
                    required: true,
                    message: "请输入部门编号",
                    trigger: "blur",
                }],
                linkMan: [{
                    required: true,
                    message: "请输入联系人",
                    trigger: "blur",
                }],
                phone: [{
                    required: true,
                    message: "请输入联系电话",
                    trigger: "blur",
                }],
            },
        };
    },
    created() {
        this.Organization();
    },

    watch: {
        filterText(val) {
            this.$refs.tree.filter(val);
        },
    },
    mounted() {
        // document.addEventListener('click', () => {
        //     if (this.documentClick) {
        //         this.UserControl()
        //         this.filterList = []
        //         this.documentClick = false
        //     }
        // })
    },
    computed: {
        ...mapGetters({
            options: "getTreeData/filtersVillage",
        }),
    },
    methods: {
        deleteUser(id) {
            axios.post(
                `rbac/sysuser/delete`, {
                    params: {
                        "userIds": id
                    }
                }).then((res) => {
                if (res && res.errorCode == "00000") {
                    this.$message("删除成功！");
                    this.UserControl();
                }
            });
        },
        resetList() {
            this.filterList = []
        },

        changeOptions() {
            this.form.subjectVillageId = "";
        },
        getIndex(val) {
            this.townIndex = val;
        },
        selectUsers(data, e) {
            console.log(data, e, this.selectOrganizationForm)
            this.selectOrganizationForm.id = data.id
            this.selectOrganizationForm.name = data.label
            this.selectOrganizationForm.phone = data.linkPhone
            this.selectOrganizationForm.linkman = data.linkMan
            this.selectOrganizationForm.number = data.value
            this.selectOrganizationForm.abbreviation = data.organShortName
            if (data.parent == 0) {
                this.selectOrganizationForm.superior = 0
            } else {
                let arr = []
                arr.push(e.parent.data.value)
                arr.push(data.value)
                this.selectOrganizationForm.superior = arr
            }
            this.selectOrganizationForm.selectArea = [data.provinceCode, data.cityCode, data.areaCode]
            this.selectOrganizationForm.selectDetails = data.detailAddress
        },

        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },


        // account: "",
        // userName: "",
        // password: "",
        // password2: "",
        // organization: [],
        // phone: "",
        // userId: "",
        // street: "",
        // level: "",
        // roleId: 3,

        adduser(id) {
            if (id > 0) {
                this.form.userId = id;
                this.isAddOrEdit = false;
            } else {
                this.form.userId = "";
                this.form.account = "";
                this.form.password = "";
                this.form.phone = "";
                this.isAddOrEdit = true;
            }
            this.$common.RolePermission(this.form).then((res) => {
                this.roleList = res.data.list;
                if (this.form.userId) {
                    this.$common.getUserDetailInfo(this.form).then((res) => {
                        console.log("userinfo", res)
                        this.form.account = res.data.list[0].username;
                        this.form.userName = res.data.list[0].realName;
                        this.form.phone = res.data.list[0].registerTele;
                        this.form.registerCard = res.data.list[0].idCard;
                        this.form.roleIds = res.data.list[0].roleIds;
                        this.form.level = res.data.list[0].userLevel;
                        if (res.data.list[0].userLevel == 4) {
                            this.form.subjectTownId = res.data.list[0].userAdministrativeCode;
                        }
                        if (res.page.list[0].userLevel == 5) {
                            this.form.subjectVillageId = res.data.list[0].userAdministrativeCode;
                        }
                        if (res.page.list[0].userLevel == 3) {
                            this.form.subjectTownId = "";
                            this.form.subjectVillageId = "";
                        }
                        this.disabled = false;
                        this.dialogFormVisible = true;
                    });
                } else {
                    this.disabled = false;
                    this.dialogFormVisible = true;
                }
            });
        },

        handleClick(row) {
            this.form = row;
            this.lookdialogFormVisible = true;
        },
        // 关闭弹框的事件
        closeDialog() {
            this.dialogFormVisible = false;
        },
        // 点击取消事件
        cancelFun() {
            this.dialogFormVisible = false;
        },

        //树形结构节点的点击事件
        handleNodeClick() {
        },
        statusChange(item) {
            console.log(item);
        },
        userStatusCn(index) {
            var Status = {
                0: "待审核",
                1: "审核通过",
                2: "审核不通过",
            };

            return Status[index];
        },
        onSearch() {
        },
        handleSizeChange(pageSize) {
            this.params.pageSize = pageSize;
            this.UserControl(this.params.pageNumber, this.params.pageSize);
        },
        currentchange(pageNumber) {
            this.params.pageNumber = pageNumber;
            this.UserControl(this.params.pageNumber, this.params.pageSize);
        },

        Organization(pageNumber = 1, pageSize = 30) {
            this.$common.Organization(pageNumber, pageSize).then((res) => {
                console.log(res)
                this.OrganizationTree = res.data.list.reverse();
                this.OrganizationTree = convertKey(this.OrganizationTree, {
                    organName: "label",
                    organCode: "value",
                });
            });
        },

        UserControl(pageNumber = 1, pageSize = 10) {
            this.$fishing.UserControl(pageNumber, pageSize).then((res) => {
                this.List = res.data.list;
                delete res.data.list;
                this.paging = res.data;
            });
        },
        handleChange(value) {
            console.log(value);
        },

        onSubmit(formName) {

            if (formName == 'AddOrganizationForm') {
                this.addOrganizationForm.detailedAddress = this.addArea[0] + "," + this.addArea[1] + "," + this.addArea[2] + "|" + this.addDetails;
         
                this.$fishing.createOriganOnSubmit(this.addOrganizationForm).then((res) => {
                    if (res && res.errorCode == "00000") {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.changeIsAdd(false);
                            }
                        })
                    } else {
                        this.$message.error(res.errorMsg)
                    }
                })
            } else if (formName == 'selectOrganizationForm') {
                this.selectOrganizationForm.detailedAddress = this.selectOrganizationForm.selectArea[0] + "," + this.selectOrganizationForm.selectArea[1] + "," + this.selectOrganizationForm.selectArea[2] + "|" + this.selectOrganizationForm.selectDetails;
                // console.log(this.selectOrganizationForm)
                this.$fishing.createOriganOnSubmit(this.selectOrganizationForm).then((res) => {
                    if (res && res.errorCode == "00000") {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.changeIsAdd(false);
                                this.resetValues();
                            }
                        })
                    } else {
                        this.$message.error(res.errorMsg)
                    }
                })
            }
        },
        resetValues() {
            this.selectOrganizationForm = {}
        }
    },
};
</script>

<style lang="scss">
.UserControl {
    padding-bottom: 15px;

    .form {
        padding: 15px 10px;
    }

    .el-card {
        width: 98%;
        margin: 15px auto 0;

        .bottom {
            display: flex;
            justify-content: flex-end;
            margin-top: 15px;
        }
    }
}
</style>
